package com.tf_cut.backend.seller.service;

import com.alibaba.fastjson.JSON;
import com.jcraft.jsch.SftpException;
import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.common.service.CommonServiceImpl;
import com.tf_cut.backend.mapper.GrantDetailMapper;
import com.tf_cut.backend.mapper.SellerAndAccountMapper;
import com.tf_cut.backend.platform.pojo.GrantReceipt;
import com.tf_cut.backend.platform.service.GrantReceiptService;
import com.tf_cut.backend.platform.vo.GrantDetailVo;
import com.tf_cut.backend.platform.vo.GrantReceiptVo;
import com.tf_cut.backend.request.DefaultMybankClient;
import com.tf_cut.backend.request.DefaultSigner;
import com.tf_cut.backend.request.MybankApiException;
import com.tf_cut.backend.request.Signer;
import com.tf_cut.backend.seller.pojo.Seller;
import com.tf_cut.backend.seller.repository.SellerRepository;
import com.tf_cut.backend.seller.vo.ReceiptMobel;
import com.tf_cut.backend.seller.vo.RefundMobel;
import com.tf_cut.backend.seller.vo.RegisterInfoMobel;
import com.tf_cut.backend.seller.vo.RegisterOpenMobel;
import com.tf_cut.backend.seller.vo.RegisterOpenVo;
import com.tf_cut.backend.seller.vo.RegisterQueryMobel;
import com.tf_cut.backend.seller.vo.SellerAndAccountVo;
import com.tf_cut.backend.seller.vo.SellerAndServiceVo;
import com.tf_cut.backend.seller.vo.SellerConfirmMobel;
import com.tf_cut.backend.seller.vo.SellerConfirmVo;
import com.tf_cut.backend.seller.vo.SellerOrderVo;
import com.tf_cut.backend.seller.vo.SellerRegisterMobel;
import com.tf_cut.backend.seller.vo.SellerRegisterQueryMobel;
import com.tf_cut.backend.seller.vo.SellerRegisterVo;
import com.tf_cut.backend.seller.vo.updateRegisterMobel;
import com.tf_cut.backend.util.ExcelToTxt;
import com.tf_cut.backend.util.HttpUtil;
import com.tf_cut.backend.util.MyConfig;
import com.tf_cut.backend.util.SFTPUtil;
import com.tf_cut.backend.util.SendMail;
import com.tf_cut.backend.util.SerialNoUtil;
import com.tf_cut.backend.util.UUIDUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.beanutils.NestedNullException;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class SellerServiceImpl extends CommonServiceImpl<SellerAndAccountVo, Seller, String> implements SellerService {

	@PersistenceContext
	private EntityManager em;
	@Autowired
	private SellerRepository sellerRepository;
	@Autowired
	private SellerAccountService sellerAccountService;
	@Autowired
	private SellerAndAccountMapper sellerAndAccountMapper;

	@Autowired
	private SellerRegisterService sellerRegisterService;

	@Autowired
	private RegisterOpenService registerOpenService;

	@Autowired
	private SellerConfirmService sellerConfirmService;

	@Autowired
	private GrantDetailMapper grantDetailMapper;

	@Autowired
	private GrantReceiptService grantReceiptService;

	@Autowired
	private SendMail sendMail;

	@Resource
	private SerialNoUtil util;

	private static Signer signer = new DefaultSigner(MyConfig.privateKey);

	@Override
	public Result<SellerAndAccountVo> insertSellerAndAccount(SellerAndAccountVo svo) {
		System.out.println(svo.getIsOld() + "==================================");
		Result<SellerAndAccountVo> result = this.save(svo); // 新建商户
		svo.setSellerId(result.getData().getSellerId());

		svo.setSellerAccount(UUIDUtil.getUUID());
		result = sellerAccountService.save(svo);
		svo.setSellerAccountId(result.getData().getSellerAccountId()); // 新建商户虚拟账号

		result.setData(svo);

		return result;
	}

	@Override
	public Result<Boolean> insertSellers(String json) {
		Result<Boolean> result = Result.of(true);
		List<SellerAndAccountVo> importData = JSON.parseArray(json, SellerAndAccountVo.class);
		int num = 0;
		try {
			for (SellerAndAccountVo seller : importData) {
				switch (num++) {
				}
				if (StringUtils.isEmpty(seller.getSellerName())) {
					result = Result.of(false);
					result.setMsg("导入失败！第" + num + "行的商户名称不能为空");
					result.setFlag(false);
					return result;
				}
				seller.setSellerState("N");// 未冻结
				this.insertSellerAndAccount(seller);
			}
		} catch (Exception e) {
			log.error("创建第" + num + "行商户失败。error=" + e.getMessage(), e);
			result = Result.of(false);
			result.setMsg("创建第" + num + "行商户失败");
			result.setFlag(false);
		}
		return result;
	}

	@Override
	public PageInfo<SellerAndAccountVo> querySellerBillList(SellerAndAccountVo sellerAndAccountVo) {
		com.github.pagehelper.PageHelper.startPage(sellerAndAccountVo.getPage(), sellerAndAccountVo.getRows());
		List<SellerAndAccountVo> list = sellerAndAccountMapper.findSellerForAdmin(sellerAndAccountVo);
		com.github.pagehelper.PageInfo<SellerAndAccountVo> pageInfo = new com.github.pagehelper.PageInfo<>(list);

		PageInfo<SellerAndAccountVo> returnPageInfo = new PageInfo<>();
		returnPageInfo.setPage(pageInfo.getPageNum());
		returnPageInfo.setPageSize(pageInfo.getPageSize());
		returnPageInfo.setRows(pageInfo.getList());
		returnPageInfo.setRecords((int) pageInfo.getTotal());
		returnPageInfo.setTotal(pageInfo.getPages());
		return returnPageInfo;
	}

	@Override
	public PageInfo<SellerAndAccountVo> querySellerBalance(SellerAndAccountVo sellerAndAccountVo) {
		com.github.pagehelper.PageHelper.startPage(sellerAndAccountVo.getPage(), sellerAndAccountVo.getRows());
		List<SellerAndAccountVo> list = sellerAndAccountMapper.querySellerBalance(sellerAndAccountVo);
		com.github.pagehelper.PageInfo<SellerAndAccountVo> pageInfo = new com.github.pagehelper.PageInfo<>(list);
		PageInfo<SellerAndAccountVo> returnPageInfo = new PageInfo<>();
		returnPageInfo.setPage(pageInfo.getPageNum());
		returnPageInfo.setPageSize(pageInfo.getPageSize());
		returnPageInfo.setRows(pageInfo.getList());
		returnPageInfo.setRecords((int) pageInfo.getTotal());
		returnPageInfo.setTotal(pageInfo.getPages());
		return returnPageInfo;
	}

	@Override
	public List<SellerAndServiceVo> findSellerService(SellerAndServiceVo avo) {

		return sellerAndAccountMapper.findSellerService(avo);
	}

	// 商户用工企业
	@Override
	public SellerAndAccountVo register(String sellerId) {
		SellerAndAccountVo svo = sellerAndAccountMapper.findBySellerRegisterRuzhu(sellerId);
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		String serialNo = util.genSerialNo("Y", "A", "3");
		SellerRegisterMobel sellerRegisterMobel = new SellerRegisterMobel();
		sellerRegisterMobel.setIsvOrgId(MyConfig.isvOrgId);
		sellerRegisterMobel.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		sellerRegisterMobel.setOutMerchantId(UUID.randomUUID().toString().replace("-", ""));
		sellerRegisterMobel.setMerchantName(svo.getSellerCompanyName());
		sellerRegisterMobel.setMerchantType("03");
		try {
			sellerRegisterMobel.setMerchantDetail(MyConfig.Base64(svo));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		sellerRegisterMobel.setDealType("01");
		sellerRegisterMobel.setMainIdentity("CORMANAGEMENT");
		sellerRegisterMobel.setSubIdentity("LAB_COR");
		sellerRegisterMobel.setBankCardParam("");
		sellerRegisterMobel.setAuthCode("");
		sellerRegisterMobel.setMcc("");
		sellerRegisterMobel.setCloudFundsInfo("");
		sellerRegisterMobel.setIdentityExt("{\"LAB_MODEL\":\"" + "PAYROLL" + "\"}");
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(sellerRegisterMobel, "ant.mybank.merchantprod.merch.register");
		System.out.println("对象转码" + resultXml);
		try {
			String sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户入驻返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				String OutMerchantId = null;
				String OrderNo = null;
				String OutTradeNo = null;
				String resultStatus = null;
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();

					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
							String resultMsg = element3.elementText("ResultMsg");
							sellerAndAccountMapper.updateStus(resultStatus, resultCode, resultMsg, svo.getSellerId());
							svo.setResultStatus(resultStatus);
							svo.setResultCode(resultCode);
							svo.setResultMsg(resultMsg);
						}
						OutMerchantId = element2.elementText("OutMerchantId");
						OrderNo = element2.elementText("OrderNo");
						OutTradeNo = element2.elementText("OutTradeNo");
					}
				}
				if (resultStatus.equals("S")) {
					SellerRegisterVo sellerRegisterVo = new SellerRegisterVo();
					// if (svo.getRegisterId() != null &&
					// !svo.getRegisterId().equals("")) {
					// sellerAndAccountMapper.updateRegisterStatus(svo.getRegisterId());
					// }
					sellerRegisterVo.setRegisterId(svo.getRegisterId());
					sellerRegisterVo.setStatus("1");
					sellerRegisterVo.setSellerId(svo.getSellerId());
					sellerRegisterVo.setOrderNo(OrderNo);
					sellerRegisterVo.setOutTradeNo(OutTradeNo);
					sellerRegisterVo.setOutMerchantId(OutMerchantId);
					sellerRegisterVo.setRegisterStatus("0");
					sellerRegisterVo.setFailReason("");
					sellerRegisterVo.setAskTime(new Timestamp(System.currentTimeMillis()));
					sellerRegisterService.save(sellerRegisterVo);
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			e.printStackTrace();
		}
		return svo;
	}

	public String photoUpload(String photoType, String picture) {
		String upload = MyConfig.uploadFile(photoType, picture);
		return upload;
	}

	/**
	 * 商户入驻查询
	 */
	@Override
	public void registerQuery(String sellerId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findBySellerRegister(sellerId);
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		SellerRegisterQueryMobel sellerRegisterQueryMobel = new SellerRegisterQueryMobel();
		sellerRegisterQueryMobel.setIsvOrgId(MyConfig.isvOrgId);
		sellerRegisterQueryMobel.setOrderNo(sellerAndAccountVo.getOrderNo());
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(sellerRegisterQueryMobel, "ant.mybank.merchantprod.merch.register.query");
		System.out.println("对象转码" + resultXml);

		String sellerRegisterVoXml;
		try {
			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户入驻查询返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				String OutMerchantId = null;
				String OrderNo = null;
				String OutTradeNo = null;
				String merchantId = null;
				String registerStatus = null;
				String failReason = null;
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							String resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
							String resultMsg = element3.elementText("ResultMsg");
							sellerAndAccountMapper.updateStus(resultStatus, resultCode, resultMsg,
									sellerAndAccountVo.getSellerId());
						}
						OutMerchantId = element2.elementText("OutMerchantId");
						OrderNo = element2.elementText("OrderNo");
						OutTradeNo = element2.elementText("OutTradeNo");
						merchantId = element2.elementText("MerchantId");
						registerStatus = element2.elementText("RegisterStatus");
						failReason = element2.elementText("FailReason");
					}
				}
				// String serialNo = util.genSerialNo("Y", "A", "3");
				SellerRegisterVo sellerRegisterVo = new SellerRegisterVo();
				sellerRegisterVo.setRegisterId(sellerAndAccountVo.getRegisterId());
				sellerRegisterVo.setSellerId(sellerAndAccountVo.getSellerId());
				sellerRegisterVo.setMerchantId(merchantId);
				sellerRegisterVo.setRegisterStatus(registerStatus);
				sellerRegisterVo.setOrderNo(OrderNo);
				sellerRegisterVo.setOutTradeNo(OutTradeNo);
				sellerRegisterVo.setOutMerchantId(OutMerchantId);
				sellerRegisterVo.setFailReason(failReason);
				sellerRegisterVo.setStatus("3");
				sellerRegisterService.save(sellerRegisterVo);
			} catch (DocumentException | UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 商户信息修改
	 * 
	 * @param sellerId
	 * @return
	 */
	@Override
	public String updateRegister(String sellerId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findBySellerRegister(sellerId);
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		updateRegisterMobel sellerRegisterMobel = new updateRegisterMobel();
		sellerRegisterMobel.setIsvOrgId(MyConfig.isvOrgId);
		sellerRegisterMobel.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		sellerRegisterMobel.setMerchantId(sellerAndAccountVo.getMerchantId());
		try {
			sellerRegisterMobel.setMerchantDetail(MyConfig.Base64(sellerAndAccountVo));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(sellerRegisterMobel, "ant.mybank.merchantprod.merch.updateMerchant");
		System.out.println("对象转码" + resultXml);

		String sellerRegisterVoXml;
		try {
			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户修改返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				String OrderNo = null;
				String OutTradeNo = null;
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							String resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
							String resultMsg = element3.elementText("ResultMsg");
							sellerAndAccountMapper.updateStus(resultStatus, resultCode, resultMsg,
									sellerAndAccountVo.getSellerId());
						}
						OrderNo = element2.elementText("OrderNo");
						OutTradeNo = element2.elementText("OutTradeNo");
					}
				}
				String serialNo = util.genSerialNo("Y", "A", "3");
				SellerRegisterVo sellerRegisterVo = new SellerRegisterVo();
				sellerRegisterVo.setRegisterId(sellerAndAccountVo.getRegisterId());
				sellerRegisterVo.setSellerId(sellerAndAccountVo.getSellerId());
				sellerRegisterVo.setStatus("2");
				sellerRegisterVo.setOrderNo(OrderNo);
				sellerRegisterVo.setOutTradeNo(OutTradeNo);
				sellerRegisterService.save(sellerRegisterVo);
			} catch (DocumentException | UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String queryRegisterInfo(String sellerId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findBySellerRegister(sellerId);
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		RegisterInfoMobel sellerRegisterMobel = new RegisterInfoMobel();
		sellerRegisterMobel.setIsvOrgId(MyConfig.isvOrgId);
		sellerRegisterMobel.setMerchantId(sellerAndAccountVo.getMerchantId());
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(sellerRegisterMobel, "ant.mybank.merchantprod.merch.query");
		System.out.println("对象转码" + resultXml);

		String MerchantDetail = null;
		try {
			String sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户查询返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							String resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
							String resultMsg = element3.elementText("ResultMsg");
							if (resultStatus.equals("U")) {
								return "未知状态";
							} else if (resultStatus.equals("F")) {
								return resultMsg;
							}
						}
						MerchantDetail = MyConfig.Base64String(element2.elementText("MerchantDetail"));
					}
				}
			} catch (DocumentException | UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			e.printStackTrace();
		}
		return MerchantDetail;
	}

	@Override
	public String regisOpen(String sellerId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findBySellerRegister(sellerId);
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		RegisterOpenMobel registerOpenMobel = new RegisterOpenMobel();
		registerOpenMobel.setIsvOrgId(MyConfig.isvOrgId);
		registerOpenMobel.setMerchantId(sellerAndAccountVo.getMerchantId());
		registerOpenMobel.setScene("CO_MANAGEMENT");
		registerOpenMobel.setParentType("MERCHANT");
		registerOpenMobel.setParentId(sellerAndAccountMapper.findByServiceMerchant(sellerId));
		registerOpenMobel.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(registerOpenMobel, "ant.mybank.bkcloudfunds.account.dynamic.parent.open");
		System.out.println("对象转码" + resultXml);
		RegisterOpenVo registerOpen = new RegisterOpenVo();
		try {
			String sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户开户返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				String resultMsg = null;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							String resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
							resultMsg = element3.elementText("ResultMsg");
						}
						registerOpen.setId(UUID.randomUUID().toString().replace("-", ""));
						registerOpen.setIsvOrgId(element2.elementText("IsvOrgId"));
						registerOpen.setMerchantId(element2.elementText("MerchantId"));
						registerOpen.setOutTradeNo(element2.elementText("OutTradeNo"));
						registerOpen.setBranchNo(element2.elementText("BranchNo"));
						registerOpen.setBranchName(element2.elementText("BranchName"));
						registerOpen.setBankCardNo(element2.elementText("BankCardNo"));
						registerOpen.setBankCertName(element2.elementText("BankCertName"));
					}
					if (!registerOpen.getMerchantId().equals("") && registerOpen.getMerchantId() != null) {
						registerOpenService.save(registerOpen);
					} else {
						sellerAndAccountMapper.updateMsg(resultMsg, sellerId);
					}
				}
			} catch (DocumentException | UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String onlinePayment(String orderId) {
		SellerOrderVo sellerOrderVo = sellerAndAccountMapper.findBySellerOrder(orderId);
		List<GrantDetailVo> GrantDetailVo = grantDetailMapper.findByOrderId(orderId);
		String excel = ExcelToTxt.excelToTxt(sellerOrderVo, GrantDetailVo);
		System.out.println(excel);
		try {
			SFTPUtil.upSftp(excel, orderId, sellerOrderVo.getMerchantId());
		} catch (SftpException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findBySellerRegister(sellerOrderVo.getSellerId());
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		SellerConfirmMobel SellerConfirm = new SellerConfirmMobel();
		SellerConfirm.setIsvOrgId(MyConfig.isvOrgId);
		SellerConfirm.setMerchantId(sellerAndAccountVo.getMerchantId());
		SellerConfirm.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		SellerConfirm.setBatchNo(orderId);
		// SellerConfirm.setRelateBatchNo("");
		double sum = sellerOrderVo.getRealAmount().doubleValue() * 100;
		SellerConfirm.setTotalAmount((int) sum);
		SellerConfirm.setPayerCardNo(sellerOrderVo.getBankCardNo());
		SellerConfirm.setTotalFeeAmount(0);
		SellerConfirm.setCurrency("CNY");
		SellerConfirm.setTotalCount(GrantDetailVo.size());
		SellerConfirm.setPayWay("01");
		SellerConfirm.setPayrollCreditType("02");
		SellerConfirm.setMemo("");
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(SellerConfirm, "ant.mybank.bkcloudfunds.comanagement.file.confirm");
		System.out.println("对象转码" + resultXml);
		String sellerRegisterVoXml;
		String IsvOrgId = null;
		String MerchantId = null;
		String OutTradeNo = null;
		String BatchNo = null;
		String resultStatus = null;
		String resultCode = null;
		String resultMsg = null;
		try {
			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("网商发放返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							resultStatus = element3.elementText("ResultStatus");
							resultCode = element3.elementText("ResultCode");
							resultMsg = element3.elementText("ResultMsg");
						}
						IsvOrgId = element2.elementText("IsvOrgId");
						MerchantId = element2.elementText("MerchantId");
						OutTradeNo = element2.elementText("OutTradeNo");
						BatchNo = element2.elementText("BatchNo");
					}
				}
				SellerConfirmVo sellerConfirm = new SellerConfirmVo();
				sellerConfirm.setId(UUID.randomUUID().toString().replace("-", ""));
				sellerConfirm.setMerchantId(MerchantId);
				sellerConfirm.setOrderId(orderId);
				sellerConfirm.setOutTradeNo(OutTradeNo);
				sellerConfirm.setBatchNo(BatchNo);
				sellerConfirm.setRelateBatchNo("");
				sellerConfirm.setResultStatus(resultStatus);
				sellerConfirm.setResultCode(resultCode);
				sellerConfirm.setResultMsg(resultMsg);
				sellerConfirm.setIsvOrgId(IsvOrgId);
				sellerConfirm.setAskTime(new Timestamp(System.currentTimeMillis()));
				sellerConfirmService.save(sellerConfirm);
			} catch (Exception e) {
			}
		} catch (Exception e) {
		}
		return resultStatus;
	}

	@Override
	public void sellerMoney() {
		List<SellerAndAccountVo> sellerAndAccountVo = sellerAndAccountMapper.findBySellerAccount();
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		for (int x = 0; x < sellerAndAccountVo.size(); x++) {
			if (sellerAndAccountVo.get(x).getBankCardNo() != null
					&& !sellerAndAccountVo.get(x).getBankCardNo().equals("")) {
				RegisterQueryMobel registerQueryMobel = new RegisterQueryMobel();
				registerQueryMobel.setIsvOrgId(MyConfig.isvOrgId);
				registerQueryMobel.setBankCardNo(sellerAndAccountVo.get(x).getBankCardNo());
				registerQueryMobel.setAccountType("01");
				// 采用非注解方式将对象转xml
				String resultXml = MyConfig.beanToXml(registerQueryMobel,
						"ant.mybank.bkcloudfunds.account.balance.query");
				System.out.println("对象转码" + resultXml);
				String sellerRegisterVoXml;
				String IsvOrgId = null;
				String BankCardNo = null;
				String Currency = null;
				String Amount = null;
				String resultStatus = null;
				String resultCode = null;
				String resultMsg = null;
				try {
					sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
					String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
					System.out.println("专户余额响应报文：" + response);
					SAXReader reader = new SAXReader();
					try {
						org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
						org.dom4j.Element root = doc.getRootElement();
						org.dom4j.Element element;
						org.dom4j.Element element2;
						org.dom4j.Element element3;
						for (Iterator i = root.elementIterator("response"); i.hasNext();) {
							element = (org.dom4j.Element) i.next();
							for (Iterator j = element.elementIterator("body"); j.hasNext();) {
								element2 = (org.dom4j.Element) j.next();
								for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
									element3 = (org.dom4j.Element) k.next();
									resultStatus = element3.elementText("ResultStatus");
									resultCode = element3.elementText("ResultCode");
									resultMsg = element3.elementText("ResultMsg");
								}
								IsvOrgId = element2.elementText("IsvOrgId");
								BankCardNo = element2.elementText("BankCardNo");
								Currency = element2.elementText("Currency");
								Amount = element2.elementText("Amount");
							}
						}
						double sum = sellerAndAccountVo.get(x).getAccountTotal().doubleValue() * 100;
						int beforeMoney = (int) sum;
						int afterMoney = Integer.parseInt(Amount);
						if (beforeMoney != afterMoney) {
							sendMail.sellerMoneyMailSend(sellerAndAccountVo.get(x).getSellerName(), beforeMoney,
									afterMoney);
						}
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}
			}
		}
	}

	@Override
	public String grantReceipt(String orderId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.getByOrderId(orderId);
		if(sellerAndAccountVo == null){
			return "未查询到发放订单";
		}
		new DefaultMybankClient(MyConfig.receiptUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		ReceiptMobel ReceiptMobel = new ReceiptMobel();
		ReceiptMobel.setIsvOrgId(MyConfig.isvOrgId);
		ReceiptMobel.setMerchantId(sellerAndAccountVo.getMerchantId());
		ReceiptMobel.setBatchNo(orderId);
		ReceiptMobel.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		String sellerRegisterVoXml;
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.receiptToXml(ReceiptMobel,
				"ant.mybank.bkcloudfunds.payrollpayment.batch.electronicreceipt.apply");
		System.out.println("对象转码" + resultXml);
		try {
			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.receiptUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("申请回单响应报文：" + response);

			GrantReceiptVo grantReceipt = new GrantReceiptVo();

			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							grantReceipt.setResultStatus(element3.elementText("ResultStatus"));
							grantReceipt.setResultCode(element3.elementText("ResultCode"));
							grantReceipt.setResultMsg(element3.elementText("ResultMsg"));
						}
						grantReceipt.setIsvOrgId(element2.elementText("IsvOrgId"));
						grantReceipt.setMerchantId(element2.elementText("MerchantId"));
						grantReceipt.setOrderNo(element2.elementText("OutTradeNo"));
						grantReceipt.setOrderNo(element2.elementText("OrderNo"));
						grantReceipt.setBatchNo(element2.elementText("BatchNo"));
					}
				}
				if (grantReceipt.getResultStatus().equals("S") || grantReceipt.getResultStatus().equals("U")) {
					grantReceiptService.save(grantReceipt);
					return "申请成功";
				}
			} catch (Exception e) {
			}
		} catch (Exception e) {
		}
		return "申请失败，请联系管理员";
	}

//	public static void main(String[] args) {
//		new DefaultMybankClient(MyConfig.receiptUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
//		RefundMobel refundMobel = new RefundMobel();
//		refundMobel.setIsvOrgId(MyConfig.isvOrgId);
//		refundMobel.setParticipantType("MERCHANT");
//		refundMobel.setParticipantId("226801000000356494927");
//		refundMobel.setRelateOrderNo("202105921302447929");
//		refundMobel.setRelateTransNo("");
//		refundMobel.setOutRefundNo(UUID.randomUUID().toString().replace("-", ""));
//		refundMobel.setRefundAmount("1");
//		refundMobel.setCurrency("CNY");
//		refundMobel.setRefundReason("测试退款");
//		String sellerRegisterVoXml;
//		String resultXml = MyConfig.beanToXml(refundMobel,"ant.mybank.bkcloudfunds.refund.apply");
//		System.out.println("对象转码" + resultXml);
//		try {
//		sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
//		String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
//		System.out.println("申请回单响应报文：" + response);
//		} catch (Exception e) {
//			
//			}
//		
////		new DefaultMybankClient(MyConfig.receiptUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
////		ReceiptMobel ReceiptMobel = new ReceiptMobel();
////		ReceiptMobel.setIsvOrgId(MyConfig.isvOrgId);
////		ReceiptMobel.setMerchantId("226801000000381489666");
////		ReceiptMobel.setBatchNo("FA01621202107020009");
////		ReceiptMobel.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
////		String sellerRegisterVoXml;
////		// 采用非注解方式将对象转xml
////		String resultXml = MyConfig.receiptToXml(ReceiptMobel,
////				"ant.mybank.bkcloudfunds.payrollpayment.batch.electronicreceipt.apply");
////		System.out.println("对象转码" + resultXml);
////		try {
////			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
////			String response = HttpUtil.doPosts(MyConfig.receiptUrl, sellerRegisterVoXml, "UTF-8");
////			System.out.println("申请回单响应报文：" + response);
////
////			GrantReceiptVo grantReceipt = new GrantReceiptVo();
////
////			SAXReader reader = new SAXReader();
////			try {
////				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
////				org.dom4j.Element root = doc.getRootElement();
////				org.dom4j.Element element;
////				org.dom4j.Element element2;
////				org.dom4j.Element element3;
////				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
////					element = (org.dom4j.Element) i.next();
////					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
////						element2 = (org.dom4j.Element) j.next();
////						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
////							element3 = (org.dom4j.Element) k.next();
////							grantReceipt.setResultStatus(element3.elementText("ResultStatus"));
////							grantReceipt.setResultCode(element3.elementText("ResultCode"));
////							grantReceipt.setResultMsg(element3.elementText("ResultMsg"));
////						}
////						grantReceipt.setIsvOrgId(element2.elementText("IsvOrgId"));
////						grantReceipt.setMerchantId(element2.elementText("MerchantId"));
////						grantReceipt.setOrderNo(element2.elementText("OutTradeNo"));
////						grantReceipt.setOrderNo(element2.elementText("OrderNo"));
////						grantReceipt.setBatchNo(element2.elementText("BatchNo"));
////					}
////				}
////				if (grantReceipt.getResultStatus().equals("S") || grantReceipt.getResultStatus().equals("U")) {
////					grantReceiptService.save(grantReceipt);
////				}
////			} catch (Exception e) {
////			}
////		} catch (Exception e) {
////		}
//			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
//			String response = HttpUtil.doPosts(MyConfig.receiptUrl, sellerRegisterVoXml, "UTF-8");
//			System.out.println("申请回单响应报文：" + response);
//
//			// GrantReceiptVo grantReceipt = new GrantReceiptVo();
//			//
//			// SAXReader reader = new SAXReader();
//			// try {
//			// org.dom4j.Document doc = reader.read(new
//			// ByteArrayInputStream(response.getBytes("UTF-8")));
//			// org.dom4j.Element root = doc.getRootElement();
//			// org.dom4j.Element element;
//			// org.dom4j.Element element2;
//			// org.dom4j.Element element3;
//			// for (Iterator i = root.elementIterator("response"); i.hasNext();)
//			// {
//			// element = (org.dom4j.Element) i.next();
//			// for (Iterator j = element.elementIterator("body"); j.hasNext();)
//			// {
//			// element2 = (org.dom4j.Element) j.next();
//			// for (Iterator k = element2.elementIterator("RespInfo");
//			// k.hasNext();) {
//			// element3 = (org.dom4j.Element) k.next();
//			// grantReceipt.setResultStatus(element3.elementText("ResultStatus"));
//			// grantReceipt.setResultCode(element3.elementText("ResultCode"));
//			// grantReceipt.setResultMsg(element3.elementText("ResultMsg"));
//			// }
//			// grantReceipt.setIsvOrgId(element2.elementText("IsvOrgId"));
//			// grantReceipt.setMerchantId(element2.elementText("MerchantId"));
//			// grantReceipt.setOrderNo(element2.elementText("OutTradeNo"));
//			// grantReceipt.setOrderNo(element2.elementText("OrderNo"));
//			// grantReceipt.setBatchNo(element2.elementText("BatchNo"));
//			// }
//			// }
//			// if (grantReceipt.getResultStatus().equals("S") ||
//			// grantReceipt.getResultStatus().equals("U")) {
//			// grantReceiptService.save(grantReceipt);
//			// }
//			// } catch (Exception e) {
//			// }
//		} catch (Exception e) {
//			
//		}
//	}

	@Override
	public String findWsMoney(String sellerId) {
		SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findWsMoney(sellerId);
		if (sellerAndAccountVo.getBankCardNo() != null && !sellerAndAccountVo.getBankCardNo().equals("")) {
			new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
			RegisterQueryMobel registerQueryMobel = new RegisterQueryMobel();
			registerQueryMobel.setIsvOrgId(MyConfig.isvOrgId);
			registerQueryMobel.setBankCardNo(sellerAndAccountVo.getBankCardNo());
			registerQueryMobel.setAccountType("01");
			// 采用非注解方式将对象转xml
			String resultXml = MyConfig.beanToXml(registerQueryMobel, "ant.mybank.bkcloudfunds.account.balance.query");
			System.out.println("对象转码" + resultXml);
			String sellerRegisterVoXml;
			String IsvOrgId = null;
			String BankCardNo = null;
			String Currency = null;
			String Amount = null;
			String resultStatus = null;
			String resultCode = null;
			String resultMsg = null;
			try {
				sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
				String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
				System.out.println("专户余额响应报文：" + response);
				SAXReader reader = new SAXReader();
				try {
					org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
					org.dom4j.Element root = doc.getRootElement();
					org.dom4j.Element element;
					org.dom4j.Element element2;
					org.dom4j.Element element3;
					for (Iterator i = root.elementIterator("response"); i.hasNext();) {
						element = (org.dom4j.Element) i.next();
						for (Iterator j = element.elementIterator("body"); j.hasNext();) {
							element2 = (org.dom4j.Element) j.next();
							for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
								element3 = (org.dom4j.Element) k.next();
								resultStatus = element3.elementText("ResultStatus");
								resultCode = element3.elementText("ResultCode");
								resultMsg = element3.elementText("ResultMsg");
							}
							IsvOrgId = element2.elementText("IsvOrgId");
							BankCardNo = element2.elementText("BankCardNo");
							Currency = element2.elementText("Currency");
							Amount = element2.elementText("Amount");
						}
					}
					if (Amount != null && !Amount.equals("")) {
						double afterMoney = Double.parseDouble(Amount) / 100;
						return String.valueOf(afterMoney);
					}
				} catch (Exception e) {
				}
			} catch (Exception e) {
			}
		}
		return "该商户未入驻网商";
	}

}
